/**
 * Created by Delicate on 2018/1/12.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    ScrollView,
    DeviceEventEmitter
} from 'react-native';

import NavBar from '../../components/NavBarView'
import {
    FormStatus,
    FormEvent,
    SubmitBtn,
    DefaultInput,
    DefaultField,
    DefaultLabel
} from '../../components/Form'
import Constants from '../../config/Constants'
import PassportService from '../../services/Passport'

let _self = null;
let _timer = null;

const validRule = {
    form: {
        mobile_code: {
            required: true,
            regExp: /\d{6}/,
            errorMsg: '请输入6位数字手机验证码'
        },
        password: {
            required: true,
            regExp: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
            errorMsg: '请输入6-20位数字字母组合密码'
        },
        current_password: {
            required: true
        }
    }
};

class Views extends React.Component {

    constructor(props) {
        super(props)
        _self = this;
        this.state = {
            formStatus: FormStatus.EDIT,
            form: {
                mobile_code: '',
                current_password: '',
                password: ''
            },
            canSend: true,
        }
    }

    componentWillMount() {

    }

    componentDidMount() {

    }
    componentWillUnmount() {
        clearInterval(_timer);
    }

    async modify() {
        const valid = FormEvent.isValid(validRule.form, _self.state.form);
        if (valid.result) {
            _self.setState({
                formStatus: FormStatus.SUBMITTING
            });
            const {result, message} = await PassportService.modify({params: _self.state.form});
            if (result) {
                DeviceEventEmitter.emit(Constants.LISTENER_LOGGING);
                const keyForPrevViewState = _self.props.navigation.state.params.prevState.pop().key;
                _self.props.navigation.goBack(keyForPrevViewState);
            }
            Toast.show(message);
            _self.formReset();
        } else {
            Toast.show(valid.message);
        }
    }

    //发送事件
    async send() {
        //判断是否可以发送
        if (_self.state.canSend) {
            //重置倒计时
            let times = Constants.SMS_INTERVAL;
            clearInterval(_timer);
            //禁用发送事件
            _self.setState({canSend: false});
            //异步发送事件
            const {result, message} = await PassportService.modifySend();
            if (result) {
                //倒计时
                _timer = setInterval(() => {
                    times--;
                    if (times > 0) {
                        _self.setState({
                            sendText: times + '秒'
                        })
                    } else {
                        //倒计时结束 恢复发送事件并清空sendText
                        _self.setState({
                            sendText: '',
                            canSend: true
                        })
                    }
                }, 1000);
            } else {
                //恢复发送事件并toast
                _self.setState({canSend: true});
                Toast.show(message);
            }
        }
    }

    //input改变触发
    inputChange(key, value) {
        let form = _self.state.form;
        form[key] = value;
        _self.setState({form}, () => {
            if (_self.state.formStatus !== FormEvent.isCompleted(validRule.form, _self.state.form)) {
                _self.setState({
                    formStatus: FormEvent.isCompleted(validRule.form, _self.state.form)
                })
            }
        });
    }

    //重置表单
    formReset() {
        const form = {
            mobile_code: '',
            current_password: '',
            password: ''
        };
        _self.setState({formStatus: FormStatus.EDIT, form})
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar host={this} title="修改密码"/>
                <ScrollView style={styles.container}>
                    <View style={styles.box}>
                        <DefaultField text={user.user_name + ' '}>
                            <DefaultLabel
                                control={this.state.formStatus}
                                textStyle={[styles.label, {
                                    color: this.state.canSend ? layout.MAIN_COLOR : layout.FORM_AUX_FONT_COLOR
                                }]}
                                onPress={() => this.send()}
                                inputValue={this.state.sendText || '获取验证码'}/>
                        </DefaultField>
                        <DefaultField text="手机验证码">
                            <DefaultInput
                                keyboardType="number-pad"
                                onChangeText={(text) => this.inputChange('mobile_code', text)}
                                inputValue={this.state.form.mobile_code}
                                control={this.state.formStatus}
                                maxLength={6}
                                placeholder="输入手机验证码"/>
                        </DefaultField>
                        <DefaultField text="原始密码">
                            <DefaultInput
                                onChangeText={(text) => this.inputChange('current_password', text)}
                                inputValue={this.state.form.current_password}
                                control={this.state.formStatus}
                                maxLength={20}
                                secureTextEntry={true}
                                placeholder="输入原始密码"/>
                        </DefaultField>
                        <DefaultField text="设置新密码">
                            <DefaultInput
                                onChangeText={(text) => this.inputChange('password', text)}
                                inputValue={this.state.form.password}
                                control={this.state.formStatus}
                                maxLength={20}
                                secureTextEntry={true}
                                placeholder="输入6-20位数字字母组合密码"/>
                        </DefaultField>
                    </View>
                    <View style={styles.btnBox}>
                        <SubmitBtn control={this.state.formStatus} text="立即修改" onPress={() => this.modify()}/>
                    </View>
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    box: {
        backgroundColor: '#fff'
    },
    label: {
        color: layout.MAIN_COLOR,
        fontSize: layout.font(32)
    },
    btnBox: {
        paddingHorizontal: layout.GAP_HORIZONTAL_LARGE
    }
})

//路由
const Modify = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'Modify',
    sign: true
};

export default Modify;